package commands

import (
	"errors"

	"github.com/larspensjo/config"
	"github.com/urfave/cli"

	"../flags"
	"../utils"
)

// Remove - remove user
func Remove(config utils.Config) cli.Command {
	return cli.Command{
		Name:     "remove",
		Usage:    "remove user",
		Category: "USER COMMANDS",
		Flags: []cli.Flag{
			flags.Flags["path"],
			cli.StringFlag{
				Name:  "name",
				Usage: "remove `NAME`",
			},
		},
		Action: makeAction(config, removeAction),
	}
}

func removeAction(conf utils.Config, git utils.Git, context *cli.Context) error {
	result, err := utils.LoadConfig(conf, git, "config")
	if err != nil {
		return err
	}

	var name = context.String("name")
	var group string
	group, err = result.String("user", name)
	if err != nil {
		return errors.New("User doesn't exist")
	}

	var info string
	info, err = result.String("session", conf.PcCode)
	if err != nil {
		return errors.New("Please login to add new user")
	}
	info, err = result.String("user", info)
	if err != nil {
		return errors.New("The Session Info is error, please relogin")
	}

	if ("master" != info) && ("manager" != info) {
		return errors.New("Please login with manager/master to remove user")
	} else if ("manager" == info) && ("developer" != group) {
		return errors.New("Manager can only remove developer")
	}

	return utils.AddConfig(conf, git, "config", func(c *config.Config) *config.Config {
		c.RemoveOption("user", name)
		return c
	})
}
